<template>
  <div class="jobs-area-page">
    <el-page-header :content="pageTitle" @back="$router.back()" />
    <el-card class="card">
      <div slot="header" class="clearfix">
        <el-row type="flex" justify="space-between" align="center">
          <span style="line-height: 36px">{{ pageTitle }}</span>
          <div>
            <el-button
              v-if="isEditMode"
              size="medium"
              type="primary"
              @click="submit"
            >保存</el-button>
            <el-button
              v-if="isEditMode"
              size="medium"
              plain
              @click="cancel"
            >取消</el-button>
            <el-button
              v-else
              size="medium"
              type="primary"
              @click="edit"
            >编辑</el-button>
          </div>
        </el-row>
      </div>

      <el-row class="search-box" type="flex" justify="start" align="middle">
        <span>地区关键词：</span>
        <el-input
          v-model="queryParams.keyword"
          style="width: 230px"
          placeholder="请输入地区关键词"
        />
      </el-row>

      <!-- 不是编辑状态，并且没有作为范围，就显示提示 -->
      <div
        v-if="!isEditMode && mapData.polygonPath.length === 0"
        class="tip-bar"
      >
        <i class="tip-icon el-icon-info" />
        <span class="tip">当前{{ queryParams.agencyName }}下暂无作业范围</span>
      </div>

      <div class="map-container">
        <div v-if="isEditMode" class="option-bar">
          <el-row type="flex" justify="start" align="middle">
            <el-button type="danger" plain @click="toggleDrawing">{{
              mapData.isDrawing ? "完成绘制" : "开始绘制"
            }}</el-button>
            <el-button
              v-if="mapData.isDrawing"
              plain
              @click="deleteInstitutionsJobsArea"
            >删除围栏</el-button>
          </el-row>
          <div class="tip-bar">
            <i class="tip-icon el-icon-info" />
            <span
              class="tip"
            >点击或拖动鼠标绘制电子围栏，右击鼠标结束图形绘制，图形不可有交叉点。完成绘制后，点击提交按钮保存。仅支持绘制单个电子围栏区域</span>
          </div>
        </div>

        <!-- :scroll-wheel-zoom="true"，滚轮缩放 -->
        <!-- @click="startNewPolyline"，鼠标左键点击事件 -->
        <!-- @rightclick="addPolyline"，鼠标右键点击事件 -->
        <!-- @mousemove="syncPolyline"，鼠标移动事件 -->
        <baidu-map
          :center="mapData.center"
          :zoom="mapData.zoom"
          :scroll-wheel-zoom="true"
          class="bm-view"
          @click="startNewPolyline"
          @rightclick="addPolyline"
          @ready="onMapReady"
        >
          <!--
                多边形
                  path：构成折线的点
                  stroke-color：折线颜色
                  stroke-opacity：折线的透明度，取值范围0 - 1
                  stroke-style：折线的样式，solid或dashed
                  stroke-weight：折线的宽度，以像素为单位
                  editing：是否可以编辑
                  fill-color：填充颜色。当参数为空时，折线覆盖物将没有填充效果
                  fill-opacity：填充的透明度，取值范围0 - 1
             -->
          <bm-polygon
            :path="mapData.polygonPath"
            stroke-color="red"
            :stroke-opacity="0.5"
            stroke-style="solid"
            :stroke-weight="2"
            :editing="mapData.isDrawing"
            :fill-color="mapData.fillColor"
            :fill-opacity="0.3"
            @lineupdate="updatePolygonPath"
          />

          <bm-local-search
            :keyword="queryParams.keyword"
            :page-capacity="3"
            class="map-location"
            :panel="true"
            :auto-viewport="true"
            @infohtmlset="searchComplete"
          />
        </baidu-map>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  getInstitutionsJobsArea,
  saveInstitutionsJobsArea,
  deleteInstitutionsJobsArea
} from '@/api/institutions-jobs-area'
/**
 * 位置搜索
 */
import BmLocalSearch from 'vue-baidu-map/components/search/LocalSearch.vue'

export default {
  components: {
    BmLocalSearch
  },
  data() {
    return {
      pageTitle: '作业范围分配',
      // 是否是编辑模式
      isEditMode: false,
      // 查询参数
      queryParams: {
        // 业务Id
        bid: '',
        // 机构名称
        agencyName: '',
        // 类型，1-机构，2-快递员
        type: 2,
        // 搜索关键字
        keyword: ''
      },
      // 地图数据
      mapData: {
        // 地图中心点（经纬度坐标）
        center: {
          lng: 0,
          lat: 0
        },
        // 多边形数组
        polygonPath: [],
        // 缩放层级
        zoom: 15,
        // 填充颜色
        fillColor: '#FF0000',
        // 是否开始绘制了
        isDrawing: false
      }
    }
  },
  created() {
    // 快递员Id
    const userId = this.$route.query.bid
    // 机构名称
    const agencyName = this.$route.query.agencyName
    this.queryParams.bid = userId
    this.queryParams.agencyName = agencyName
    // 获取作业范围
    this.getInstitutionsJobsArea()
  },
  methods: {
    // 获取作业范围
    async getInstitutionsJobsArea() {
      const result = await getInstitutionsJobsArea(
        this.queryParams.bid,
        this.queryParams.type
      )
      console.log(result)

      const mapResource = result.data

      // 更新地图的经度、纬度
      this.mapData.center = {
        lng: mapResource.longitude,
        lat: mapResource.latitude
      }

      // 回显多边形
      const polygonList = mapResource.polygon || []
      this.mapData.polygonPath = polygonList.map((item) => {
        return {
          lng: item.longitude,
          lat: item.latitude
        }
      })
    },
    // 地图初始化完毕
    onMapReady({ BMap, map }) {
      // console.log(BMap, map)
      console.log('百度地图 => 初始化完毕...')
      // 设置初始中心点的经纬度
      this.mapData.center.lng = 116.404
      this.mapData.center.lat = 39.915
      // 缩放等级
      this.mapData.zoom = 10
    },
    // 切换开始绘制和完成绘制
    async toggleDrawing() {
      this.mapData.isDrawing = !this.mapData.isDrawing
    },
    // 删除作业范围
    async deleteInstitutionsJobsArea() {
      try {
        const result = await deleteInstitutionsJobsArea(
          this.queryParams.bid,
          this.queryParams.type
        )
        console.log(result)
        console.log('删除作业范围 => 成功')
        this.$message.success('删除成功')
        // 重新拉取作业范围数据
        this.getInstitutionsJobsArea()
        // 结束绘制
        this.mapData.isDrawing = false
      } catch (e) {
        console.log('删除作业范围 => 失败', e)
      }
    },
    // POI搜索完毕
    searchComplete() {
      console.log('POI搜索完毕...')
    },
    // 更新多边形
    updatePolygonPath(e) {
      console.log('更新多边形...')
      this.mapData.polygonPath = e.target.getPath()
    },
    // 编辑
    edit() {
      this.isEditMode = !this.isEditMode
    },
    // 鼠标左键，开始一个新的多边形
    startNewPolyline(e) {
      // 没有开始绘制，不处理
      if (!this.mapData.isDrawing) {
        return
      }

      // 添加点击坐标到数组中
      this.mapData.polygonPath.push({
        lng: e.point.lng,
        lat: e.point.lat
      })
    },
    // 鼠标移动，同步连线
    syncPolyline(e) {
      // 没有开始绘制，不处理
      if (!this.mapData.isDrawing) {
        return
      }

      const polygonPath = this.mapData.polygonPath

      // 如果没有设置过第一个坐标点，则忽略
      let pointObj = polygonPath[polygonPath.length - 1]
      if (!pointObj) {
        return
      }

      // console.log(`更新前坐标：[${pointObj.lng},${pointObj.lat}]`)
      pointObj = {
        lng: e.point.lng,
        lat: e.point.lat
      }
      // console.log(`更新后坐标：[${pointObj.lng},${pointObj.lat}]`)

      // 通知Vue更新视图
      this.$set(this.mapData, 'polygonPath', polygonPath)
    },
    // 右键，结束绘制
    addPolyline(e) {
      this.mapData.isDrawing = false
    },
    // 保存
    async submit() {
      try {
        // 结束绘制
        this.mapData.isDrawing = false
        const result = await saveInstitutionsJobsArea(this.mapData)
        console.log(result)
        console.log('保存绘制 => 成功')
        this.$message.success('提交成功')
      } catch (e) {
        console.log('保存绘制 => 失败', e)
      }
    },
    // 取消
    cancel() {
      // 结束编辑
      this.isEditMode = false
    }
  }
}
</script>

<style lang="scss" scoped>
.jobs-area-page {
  padding: 20px;
  padding-top: 23px;
  background-color: #f3f4f7;
  min-height: 100vh;

  .card {
    margin-top: 20px;
  }

  .search-box {
    span {
      color: #20232a;
      font-weight: 400;
      font-size: 14px;
    }
  }

  // 操作栏
  .tip-bar {
    text-align: center;
    background-color: rgb(255, 245, 231);
    margin-top: 10px;

    .tip-icon {
      color: rgb(198, 126, 18);
    }

    .tip {
      font-size: 12px;
      color: rgb(198, 126, 18);
      height: 30px;
      line-height: 30px;
      text-align: left;
      padding-left: 10px;
      margin: 12px 0;
    }
  }

  .map-container {
    position: relative;
    height: 648px;
    margin-top: 20px;
    // background-color: blue;

    .bm-view {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
    }

    .option-bar {
      position: absolute;
      background-color: #fff;
      padding-bottom: 10px;
      left: 0;
      top: 0;
      width: 100%;
      z-index: 999;
    }
  }
}
</style>
